/**
 * @description 验收信息服务层
 * @date 2020-08-21 14:08
 * @auth LI
 */

const { AcceptanceInfo, Account } = require('../db/model/index')
const axios = require('axios')
const querystring = require('querystring')
const { setHouseOwner } = require('../cache/phoneCode')
const { formatDuring } = require('../utils/dateTime')

const {
  SMS_BASE_URL,
  API_ID,
  API_KEY
} = require('../conf/secretKeys')

/**
 * 获取账号信息
 * @param {number} houseOwnerId 账号 id
 */
async function getAccountInfo(houseOwnerId) {
  // 查询条件
  const whereOpt = {
    id: houseOwnerId
  }
  
  // 查询
  const result = await Account.findOne({
    where: whereOpt
  })
  
  return result
}

/**
 * 获取验收信息
 * @param {number} workerAccountId 对应工人账号 id
 * @param {number} houseInfoId 对应房源信息 id
 * @param {number} typeLevel 对应账号类型
 */
async function getAcceptanceInfo({ workerAccountId, houseInfoId, typeLevel }) {
  // 查询条件
  const whereOpt = {}
  if (workerAccountId) {
    Object.assign(whereOpt, { workerAccountId })
  }
  if (houseInfoId) {
    Object.assign(whereOpt, { houseInfoId })
  }
  if (typeLevel) {
    Object.assign(whereOpt, { typeLevel })
  }

  // 查询
  const result = await AcceptanceInfo.findOne({
    where: whereOpt
  })
  if (result) {
    result.dataValues.acceptanceTime = formatDuring(result.dataValues.acceptanceTime)
  }

  return result
}

/**
 * 发送验收码给业主
 * @param {string} phone 手机号账号
 * @param {number} workerAccountId 对应工人账号 id
 * @param {number} houseInfoId 对应房源信息 id
 * @param {number} typeLevel 对应账号类型
 */
async function sendSMSCodeByPhone({ phone, workerAccountId, houseInfoId, typeLevel }) {
  const code = Math.floor(Math.random() * (9999 - 1000)) + 1000
  const content = `您的验收码是：${code}，请验收确认装修之后，发送给工人确认，如非本人操作，可不用理会！`
  const data = {
    account: API_ID,
    password: API_KEY,
    mobile: phone,
    content,
    format: 'json'
  }
  // util.inspect(result)
  const result = await axios.post(SMS_BASE_URL, querystring.stringify(data)).then(response => {
    const resData = response.data
    // 设置一个长期验证码失效时间
    setHouseOwner(phone, String(code), workerAccountId, houseInfoId, typeLevel)
    if (resData.code !== 2) {
      throw new Error(resData.msg)
    }
    return resData
  }).catch(error => {
    console.error(error)
    throw new Error(error)
  })
  
  return result.msg
}

/**
 * 创建验收信息
 * @param {number} workerAccountId 对应工人账号 id
 * @param {number} houseInfoId 对应房源信息 id
 * @param {number} typeLevel 对应账号类型
 * @param {string} acceptancePhoto 验收图片
 * @param {string} acceptanceTime 验收时间
 * @param {string} remark 备注/要求
 */
async function createAcceptanceInfo({ workerAccountId, houseInfoId, typeLevel, acceptancePhoto, acceptanceTime, remark }) {
  const result = await AcceptanceInfo.create({
    workerAccountId,
    houseInfoId,
    typeLevel,
    acceptancePhoto,
    acceptanceTime,
    remark
  })
  
  return result
}

/**
 * 修改验收信息
 * @param {number} id 验收信息 id
 * @param {number} workerAccountId 对应工人账号 id
 * @param {number} houseInfoId 对应房源信息 id
 * @param {number} typeLevel 对应账号类型
 * @param {Date} acceptanceTime 验收时间
 * @param {string} reserve 验收评价
 */
async function updateAcceptanceInfoById({ id, workerAccountId, houseInfoId, typeLevel, acceptanceTime, reserve }) {
  // 拼接查询条件
  const whereData = {}
  if (acceptanceTime) {
    whereData.acceptanceTime = acceptanceTime
  }
  if (reserve) {
    whereData.reserve = reserve
  }
  let whereDataId = {}
  if (id) {
    whereDataId = { id }
  } else {
    whereDataId = {
      workerAccountId,
      houseInfoId,
      typeLevel,
    }
  }
  const result = await AcceptanceInfo.update(whereData, {
    where: whereDataId
  })
  
  return result[0] > 0
}

module.exports = {
  createAcceptanceInfo,
  getAcceptanceInfo,
  getAccountInfo,
  sendSMSCodeByPhone,
  updateAcceptanceInfoById
}
